package com.toutou.base.fragment

import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import com.toutou.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.getVmClazz
import me.hgj.jetpackmvvm.ext.inflateBindingWithGeneric

abstract class BaseFragment<VM : BaseViewModel, DB : ViewDataBinding>  : Fragment() {

    abstract fun initFragmentNameType(): FragmentNameType

    enum class FragmentNameType {
        NONE,

    }

//    要动态获取Fragment的名字，否则切换语言 不生效
    companion object{
        @JvmStatic
        fun getFragmentName(fragmentNameType: FragmentNameType) : String {
            return when(fragmentNameType){
                FragmentNameType.NONE -> {
                    "fragment"
                }
            }
        }
    }


    private val handler = Handler()
    //是否第一次加载
    private var isFirst: Boolean = true

    lateinit var mViewModel: VM
    //该类绑定的 ViewBinding
    private var _binding: DB? = null
    val mViewBind: DB get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding  = inflateBindingWithGeneric(inflater,container,false)
        return mViewBind.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        isFirst = true
        mViewModel = ViewModelProvider(this)[getVmClazz(this)]
        firstInitView(savedInstanceState)
    }
    /**
     * 初始化view
     */
    abstract fun firstInitView(savedInstanceState: Bundle?)

    /**
     * 懒加载
     */
    abstract fun onLazyInitView()

    override fun onResume() {
        super.onResume()
        onVisible()
        view?.requestLayout()
        view?.invalidate()
    }

    /**
     * 延迟加载 防止 切换动画还没执行完毕时数据就已经加载好了，这时页面会有渲染卡顿  bug
     * 这里传入你想要延迟的时间，延迟时间可以设置比转场动画时间长一点 单位： 毫秒
     * 不传默认 300毫秒
     * @return Long
     */
    open fun lazyLoadTime(): Long {
        return 300
    }

    /**
     * 是否需要懒加载
     */
    private fun onVisible() {
        if (lifecycle.currentState == Lifecycle.State.STARTED && isFirst) {
            // 延迟加载 防止 切换动画还没执行完毕时数据就已经加载好了，这时页面会有渲染卡顿
            handler.postDelayed({
                isFirst = false
                onLazyInitView() //在isFirst = false;之后执行，便于onRefreshData中使用isFirst判断是否是第一次加载
            }, lazyLoadTime())
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}